package com.ip.getip.service.impl;

import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.ip.getip.util.FileImg;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description TODO
 * @Author leixin
 * @Date 2019/9/28 下午8:45
 * @Version 1.0
 **/
@Service
public class FileImpl {
    @Value("${url.anime}")
    private String anime;
    @Value("${url.home}")
    private String home;
    @Value("${url.path}")
    private String path;
    public String fileImg() throws Exception {
        WebClient client = new WebClient();
        client.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
        client.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        client.getOptions().setActiveXNative(false);
        client.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
        client.getOptions().setJavaScriptEnabled(false); //很重要，启用JS
        client.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX
        //允许cookie
        client.getCookieManager().setCookiesEnabled(true);
        // 获取某网站页面
        HtmlPage html = client.getPage(home);
        //执行按钮
        DomElement password = html.getElementById("fwin_dialog_submit");
        if (password != null) {
            password.click();
            html = client.getPage(anime);
        }
        Document parse = Jsoup.parse(html.asXml());
        //获取cookie
        Set<Cookie> cookies = client.getCookieManager().getCookies();
        Map<String, String> responseCookies = new HashMap<String, String>();
        //组装cookie
        StringBuilder cookie = new StringBuilder();
        for (Cookie c : cookies) {
            responseCookies.put(c.getName(), c.getValue());
            cookie.append(c.getName() + "=" + c.getValue() + ";");
        }
        List<Element> infoListEle = parse.getElementsByAttributeValue("class", "c1");
        List<String> urlList = new ArrayList();
        infoListEle.forEach(e -> {
            urlList.add(e.getElementsByTag("a").attr("href") + "|" + e.getElementsByTag("a").text());
        });
        urlList.forEach(l -> {
            String paths = path + l.split("\\|")[1];
            //创建文件夹
            String mkdir = FileImg.mkdir(paths);
            try {
                FileImg.getImg(l.split("\\|")[0], mkdir + "/", cookie.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return "成功";
    }
}
